/**
 * TODO
 */
package com.bci.pwtz.service.impl;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.DypdxMapper;
import com.bci.pwtz.mysql.model.Dypdx;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.DypdxService;

/**
 * TODO
 * 
 * @author ICLNetwork Team
 * @version 3.0
 */
@Service
public class DypdxServiceImpl implements DypdxService {
    private DypdxMapper objMapper;

    private BusinessRefService businessRefService;
    
    private CompanyService companyService;
    public DypdxMapper getObjMapper() {
        return objMapper;
    }

    public void setObjMapper(DypdxMapper objMapper) {
        this.objMapper = objMapper;
    }

    public BusinessRefService getBusinessRefService()
    {
        return businessRefService;
    }

    public void setBusinessRefService(BusinessRefService businessRefService)
    {
        this.businessRefService = businessRefService;
    }

    public CompanyService getCompanyService() {
        return companyService;
    }

    public void setCompanyService(CompanyService companyService) {
        this.companyService = companyService;
    }

    private static final Logger _logger = Logger.getLogger(PdbyqServiceImpl.class);

    @Override
    public Dypdx add(Dypdx dypdx) throws PwtzDatabaseException {
        if (_logger.isDebugEnabled()) {
            _logger.debug("add:dypdx=" + dypdx.toString());
        }
        if (dypdx == null) {
            if (_logger.isDebugEnabled()) {
                _logger.debug("add,dypdx is null");
            }
            return null;
        } else {
            /*UUID uuid = UUID.randomUUID();
            dypdx.setDeviceid(uuid.toString());*/
            dypdx.setStatus(1);
            dypdx.setLastmodifiedtime(new Date());
            dypdx.setCreatedate(new Date());
        }
        try {
            objMapper.insertSelective(dypdx);
        } catch (DataAccessException _e) {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return dypdx;
    }

    @Override
    public int delete(String dypdxId) throws PwtzDatabaseException, CanNotDeleteException {
        int result = 0;
        if (_logger.isDebugEnabled()) {
            _logger.debug("delete:dypdxId=" + dypdxId);
        }
        try {
            Boolean bl = businessRefService.canDelete("T_DYPDX", dypdxId);

            if (!bl) {
                throw new CanNotDeleteException();
            }
            result = objMapper.deleteById(dypdxId,new Date());
        } catch (DataAccessException _e) {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public int update(Dypdx dypdx) throws PwtzDatabaseException {
        int result = 0;
        if (_logger.isDebugEnabled()) {
            _logger.debug("update:dypdx=" + dypdx.toString());
        }
        if (dypdx == null) {
            if (_logger.isDebugEnabled()) {
                _logger.debug("update,dypdx is null");
            }
            return 0;
        }else{
            dypdx.setLastmodifiedtime(new Date());
        }
        try {
            result = objMapper.updateByPrimaryKeySelective(dypdx);
        } catch (DataAccessException _e) {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public Dypdx load(String dypdxId) throws PwtzDatabaseException {
        if (_logger.isInfoEnabled()) {
            _logger.info("load:dypdxId=" + dypdxId);
        }
        Dypdx dypdx = null;
        try {
            dypdx = objMapper.selectByPrimaryKey(dypdxId);
        } catch (DataAccessException e) {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (dypdx != null) {
            _logger.debug("load:result dypdx=" + dypdx.toString());
        }
        return dypdx;
    }

    @Override
    public PaginationList<Dypdx> findDypdx(String deviceName,Long companyid, int portalType,String[] medLineCodes,String lineCode,String beginTime, String endTime, int pageSize, int pageNo,String currentDeviceId)
            throws PwtzDatabaseException {
        PaginationList<Dypdx> paginationList = new PaginationList<Dypdx>();

        if (_logger.isInfoEnabled()) {
            _logger.info("findDybx:|deviceName=" + deviceName+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyid="+companyid+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|lineCode="+lineCode+"|pageSize="+pageSize+"|pageNo="+pageNo);
        }
        List<Dypdx> list = null;
        int beginIndex = pageSize * pageNo - pageSize;
        String companyidStr = "";
        String[] companyids=null;
        if(portalType==1){
            companyidStr = companyService.findChildrensId(companyid,null);
            if(companyidStr!=null && companyidStr.length()>0){
                companyidStr= companyidStr.substring(0,companyidStr.length()-1);
                companyids =companyidStr.split(",");
            }
        }
        try {
            list = objMapper.selectDeviceList(deviceName,companyid, companyids, portalType,medLineCodes,lineCode, beginTime, endTime, beginIndex, pageSize,currentDeviceId);
        } catch (DataAccessException e) {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list != null) {
            _logger.debug("findDypdx:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage = 1;
        if (pageSize != 0) {
            try {
                totalCount = objMapper.selectDeviceCount(deviceName,companyid, companyids, portalType,medLineCodes,lineCode, beginTime, endTime);
            } catch (DataAccessException e) {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        } else {
            pageNo = 1;
            if (list != null && list.size() > 0) {
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public List<Dypdx> getSamePreDeviceList(String deviceid) throws PwtzDatabaseException
    {
        List<Dypdx> list=null;
        if(_logger.isDebugEnabled()){
            _logger.debug("getSamePreDeviceList : deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(_logger.isDebugEnabled()){
                _logger.debug("getSamePredDeviceList,deviceid is disabled!");
            }
            return list;
        }
        try{
            list=objMapper.getSamePreDeviceList(deviceid);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
    }
    
    @Override
    public boolean deleteDevice(String deviceid) throws PwtzDatabaseException, CanNotDeleteException
    {
        boolean flag=true;
        if(_logger.isDebugEnabled()){
            _logger.debug("deleteDevice:deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(_logger.isDebugEnabled()){
                _logger.debug("deleteDevice,deviceid is disable");
            }
            return flag=false;
        }
        List<Dypdx> list=null;
        int result=0;
        try{
            list=getSamePreDeviceList(deviceid);
            if(list!=null&&list.size()>0){
                for(Dypdx device : list){
                    List<Dypdx> dlist=getSamePreDeviceList(device.getDeviceid());
                    if(dlist!=null && dlist.size()>0){
                        deleteDevice(device.getDeviceid());
                    }
                    result=delete(device.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                    
                }
            }
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return flag;
    }
    @Override
	public int updateLastSyncDevice(Long companyId, String lastSyncTime)  throws PwtzDatabaseException{
		int result=0;
		try {
			result=objMapper.updateLastSyncDevice(companyId, lastSyncTime);
		} catch (DataAccessException e) {
			_logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
		}
		return result;
	}
}
